#include "SparkEffect.h"
#include "Resource.h"
#include <string>
#include"GlobalResManager.h"
USING_NS_CC;
using namespace std;

SparkEffect::SparkEffect()
{
}

SparkEffect::~SparkEffect()
{
}
bool SparkEffect::init()
{
    if (!Sprite::init())
    {
        return false;
    }

   
    m_spark1 = Sprite::createWithSpriteFrameName("explode2.png");

    m_spark2 = Sprite::createWithSpriteFrameName("explode3.png");

    g_sharedGameLayer->addSpark(m_spark1);
    g_sharedGameLayer->addSpark(m_spark2);
    GlobalResManager::getInstance()->getSparks().pushBack(this);
    return true;
}

//
void SparkEffect::reset(Point pos)
{
    m_spark1->setPosition(pos);
    m_spark1->setScale(1.2f);
    m_spark1->setOpacity(255);
   
    
    m_spark2->setPosition(pos);
    m_spark2->setScale(1.2f);
    m_spark2->setRotation(cocos2d::random(0, 360));
    m_spark2->setOpacity(255);


    auto right = RotateBy::create(m_duration, 45);
    auto scaleBy = ScaleBy::create(m_duration, 3, 3);
    auto seq = Sequence::create(FadeOut::create(m_duration), CallFunc::create(CC_CALLBACK_0(SparkEffect::destroy, this)),nullptr);

    m_spark1->runAction(right);
    m_spark1->runAction(scaleBy);
    m_spark1->runAction(seq);

    m_spark2->runAction(scaleBy->clone());
    m_spark2->runAction(seq->clone());

}
void SparkEffect::destroy()
{
    m_active = false;
    m_spark1->setVisible(false);
    m_spark2->setVisible(false);
};

SparkEffect *SparkEffect::getOrCreateSparkEffect(Point pos)
{
    SparkEffect* selChild = nullptr;
    for (auto item: GlobalResManager::getInstance()->getSparks()) {
        selChild = (SparkEffect*)item;
        if (selChild->m_active == false) {
            selChild->m_active = true;
            selChild->m_spark1->setVisible(true);
            selChild->m_spark2->setVisible(true);
            selChild->reset(pos);
            return selChild;
        }
    }
    SparkEffect*  spark = SparkEffect::create();
    spark->reset(pos);
    return spark;
};
void SparkEffect::preSet() 
{
    
    for (int  i = 0; i < 6; i++) {
        SparkEffect* sparkEffect = SparkEffect::create();
        sparkEffect->m_active = false;
        sparkEffect->m_spark1->setVisible(false);
        sparkEffect->m_spark2->setVisible(false);
    }
};
